/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Login;

import DAO.Usuario.HibernateUtil;
import Model.User;
import com.google.gson.Gson;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.hibernate.Session;

/**
 *
 * @author pedro
 */
@Path("/enviaSenha")
public class EnviaSenha {
        
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response enviaSenha(User login) {

        Gson gson = new Gson();
        Session session = null;
                
        String response = null;

        try {
            session=HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            List<User> result = session.createQuery("From User WHERE email=? ")
                    .setString(0, login.getEmail())
                    .list();
            HibernateUtil.commitTransaction();

            if (result.isEmpty() == false) {
                enviaEmailSimples(result.get(0).getEmail(),result.get(0).getNome(),result.get(0).getSenha());
                response ="OK";
            } else {
                response = "Fail";
            }
        } catch (Exception e) {
            response = "Error";

            session.getTransaction().rollback();
        } finally {
            HibernateUtil.closeSession();
            return Response.status(201).entity(response).build();
        }
    }
    
    
    
    
    
    
     public void enviaEmailSimples(String userEmail,String nome,String senha) throws EmailException {  
          
        SimpleEmail email = new SimpleEmail();  
        email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail  
        email.addTo(userEmail,nome); //destinatário  
        email.setFrom("portalcidadaoinfo@gmail.com", "Portal cidadao"); // remetente  
        email.setSubject("Recuperação de senha"); // assunto do e-mail  
        email.setMsg("A sua senha é: " +senha); //conteudo do e-mail  
        email.setAuthentication("portalcidadaoinfo", "tcc2013ufpr");  
        email.setSmtpPort(465);  
        email.setSSL(true);  
        email.setTLS(true);  
        email.send();     
    }  
    
}
